package com.z.ssmdemo;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MyServlet extends HttpServlet {
    Connection con;

    @Override
    public void init() {
        String driver = getInitParameter("driver");
        String url = getInitParameter("url");
        String name = getInitParameter("user");
        String pass = getInitParameter("password");
        try {
            Class.forName(driver);
            con= DriverManager.getConnection(url,name,pass);
        }catch(ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }
    private static final long serialVersionUID = 1L;

    /**
     * Default constructor.
     */
    public MyServlet() {
        // TODO Auto-generated constructor stub
    }

    /**
     *
     spring:
     datasource:
     #MySQL配置
     driverClassName: com.mysql.cj.jdbc.Driver
     url: jdbc:mysql://49.235.88.75:3306/gulimall_ums?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
     username: zhanghaonan
     password: hadoop123456
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out=resp.getWriter();

        String uri = req.getRequestURI();
        String contextPath = req.getContextPath();
        String servletPath = req.getServletPath();
        uri = uri.substring((contextPath + servletPath).length());
        if ("/login".equals(uri)){
            String bookName=req.getParameter("bookName");
            ResultSet rst=null;
            out.println("<table border=1><tr><td>图书名</td><td>出版社</td><td>价格</td></tr>");
            try {
                while(rst.next()) {
                    out.println("<tr>");
                    out.println("<td>"+rst.getString("bookname")+"</td>");
                    out.println("<td>"+rst.getString("publisher")+"</td>");
                    out.println("<td>"+rst.getString("price")+"</td>");
                    out.println("</tr>");
                }
                out.println("</table>");
                rst.close();
            }catch(Exception e) {

            }
        }

        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
